<template>
  <div class="score-query">
    <!-- 顶部搜索栏 -->
    <div class="header-search">
      <el-card class="search-card">
        <el-form
          ref="searchFormRef"
          :model="searchForm"
          :inline="true"
          label-width="80px"
          class="search-form"
        >
          <el-form-item label="比赛项目">
            <el-select
              v-model="searchForm.eventId"
              placeholder="请选择比赛项目"
              clearable
              style="width: 200px"
            >
              <el-option
                v-for="event in eventOptions"
                :key="event.id"
                :label="event.name"
                :value="event.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="运动员" v-if="!isAthlete">
            <el-input
              v-model="searchForm.athleteName"
              placeholder="请输入运动员姓名"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          
          <!-- 运动员用户显示提示信息 -->
          <el-form-item v-if="isAthlete">
            <el-alert
              title="您当前查看的是自己的成绩记录"
              type="info"
              :closable="false"
              show-icon
            />
          </el-form-item>
          
          <el-form-item label="参赛组别">
            <el-select
              v-model="searchForm.group"
              placeholder="请选择组别"
              clearable
              style="width: 150px"
            >
              <el-option label="男子组" value="男子组" />
              <el-option label="女子组" value="女子组" />
              <el-option label="混合组" value="混合组" />
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 成绩列表 -->
    <div class="score-list">
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span class="card-title">成绩查询结果</span>
            <div class="header-actions">
              <el-button type="success" @click="handleExport">
                <el-icon><Download /></el-icon>
                导出Excel
              </el-button>
            </div>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="scoreList"
          style="width: 100%"
          stripe
          border
          empty-text="暂无成绩数据"
        >
          <el-table-column prop="eventName" label="比赛项目" min-width="120" show-overflow-tooltip />
          <el-table-column prop="athleteName" label="运动员姓名" min-width="100" show-overflow-tooltip />
          <el-table-column prop="athleteNumber" label="参赛号码" width="100" align="center" />
          <el-table-column prop="group" label="参赛组别" width="100" align="center" />
          <el-table-column prop="score" label="成绩" width="120" align="center">
            <template #default="{ row }">
              <span class="score-value">{{ formatScore(row.score, row.unit) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="ranking" label="排名" width="80" align="center">
            <template #default="{ row }">
              <el-tag
                v-if="row.ranking <= 3"
                :type="getRankingTagType(row.ranking)"
                effect="dark"
              >
                第{{ row.ranking }}名
              </el-tag>
              <span v-else>第{{ row.ranking }}名</span>
            </template>
          </el-table-column>
          <el-table-column prop="recordTime" label="创建时间" width="160" align="center">
            <template #default="{ row }">
              {{ formatDateTime(row.recordTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="judgeNames" label="裁判员" min-width="120" show-overflow-tooltip />
          <el-table-column label="操作" width="120" fixed="right" align="center">
            <template #default="{ row }">
              <el-button
                type="primary"
                link
                @click="handleViewDetail(row)"
              >
                <el-icon><View /></el-icon>
                详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
        <el-pagination
          :current-page="pagination.page"
          :page-size="pagination.size"
            :total="pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>

    <!-- 成绩详情对话框 -->
    <el-dialog
      v-model="detailDialog.visible"
      title="成绩详情"
      width="60%"
      :before-close="handleCloseDetail"
    >
      <div v-if="detailDialog.data" class="score-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="比赛项目">{{ detailDialog.data.eventName || '无' }}</el-descriptions-item>
          <el-descriptions-item label="运动员姓名">{{ detailDialog.data.athleteName || '无' }}</el-descriptions-item>
          <el-descriptions-item label="参赛号码">{{ detailDialog.data.athleteNumber || '无' }}</el-descriptions-item>
          <el-descriptions-item label="参赛组别">{{ detailDialog.data.group || '无' }}</el-descriptions-item>
          <el-descriptions-item label="成绩">
            <span class="score-highlight">{{ formatScore(detailDialog.data.score, detailDialog.data.unit) || '无' }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="排名">
            <el-tag
              v-if="detailDialog.data.ranking && detailDialog.data.ranking <= 3"
              :type="getRankingTagType(detailDialog.data.ranking)"
              effect="dark"
            >
              第{{ detailDialog.data.ranking }}名
            </el-tag>
            <span v-else-if="detailDialog.data.ranking">第{{ detailDialog.data.ranking }}名</span>
            <span v-else>无</span>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(detailDialog.data.recordTime) || '无' }}</el-descriptions-item>
          <el-descriptions-item label="裁判员">{{ detailDialog.data.judgeNames || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="detail-remark">
          <h4>备注信息</h4>
          <el-input
            :value="detailDialog.data.remark || '无'"
            type="textarea"
            :rows="3"
            readonly
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDetail">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Download,
  View
} from '@element-plus/icons-vue'
import { getScoreList, exportScoreData } from '@/api/score'
import { getEventListSimple } from '@/api/event'
import { useUserStore } from '@/stores/user'

// 用户store
const userStore = useUserStore()

// 判断是否为运动员
const isAthlete = computed(() => {
  return userStore.roles.includes('ATHLETE') || 
         userStore.roles.includes('athlete') || 
         (userStore.userInfo?.username && userStore.userInfo.username.startsWith('athlete'))
})

// 搜索表单
const searchFormRef = ref()
const searchForm = reactive({
  eventId: '',
  athleteName: '',
  group: ''
})

// 列表数据
const loading = ref(false)
const scoreList = ref([])
const eventOptions = ref([])

// 分页
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 详情对话框
const detailDialog = reactive({
  visible: false,
  data: null
})

// 搜索成绩
const handleSearch = async () => {
  pagination.page = 1
  await loadScoreList()
}

// 重置搜索
const handleReset = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}

// 加载成绩列表
const loadScoreList = async () => {
  try {
    loading.value = true
    const params = {
      current: pagination.page,  // 使用current而不是page，匹配后端参数
      size: pagination.size,
      ...searchForm
    }
    
    // 如果是运动员，后端会自动限制只查询自己的成绩，前端不需要额外处理
    // 但可以清空运动员姓名搜索条件，因为运动员只能看自己的成绩
    if (isAthlete.value) {
      delete params.athleteName
      console.log('运动员用户，后端将自动限制查询范围')
    }
    
    console.log('成绩查询参数:', params)
    const response = await getScoreList(params)
    console.log('成绩查询响应:', response)
    
    if (response.data && response.data.records) {
      scoreList.value = response.data.records || []
      pagination.total = response.data.total || 0
    } else {
      scoreList.value = []
      pagination.total = 0
    }
  } catch (error) {
    console.error('加载成绩列表失败:', error)
    ElMessage.error('加载成绩列表失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 加载比赛项目选项
const loadEventOptions = async () => {
  try {
    // 尝试获取所有状态的比赛项目，不限制状态
    const response = await getEventListSimple()
    console.log('比赛项目API响应:', response)
    if (response.data && Array.isArray(response.data)) {
      // 返回的是数组
      eventOptions.value = response.data.map(event => ({
        id: event.id,
        name: event.eventName || event.name
      }))
    } else if (response.data && response.data.records) {
      // 如果返回的是分页数据
      eventOptions.value = response.data.records.map(event => ({
        id: event.id,
        name: event.eventName || event.name
      }))
    } else {
      console.warn('比赛项目数据格式异常:', response.data)
      eventOptions.value = []
    }
    console.log('处理后的比赛项目选项:', eventOptions.value)
    
    // 如果还是没有数据，显示提示
    if (eventOptions.value.length === 0) {
      ElMessage.warning('暂无比赛项目数据，请联系管理员添加项目')
    }
  } catch (error) {
    console.error('加载比赛项目失败:', error)
    ElMessage.error('加载比赛项目失败: ' + (error.message || '未知错误'))
  }
}

// 查看详情
const handleViewDetail = (row) => {
  detailDialog.data = { ...row }
  detailDialog.visible = true
}

// 关闭详情对话框
const handleCloseDetail = (done) => {
  detailDialog.visible = false
  detailDialog.data = null
  if (typeof done === 'function') {
    done()
  }
}

// 导出Excel
const handleExport = async () => {
  try {
    const params = { ...searchForm }
    await exportScoreData(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.size = size
  pagination.page = 1
  loadScoreList()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.page = page
  loadScoreList()
}

// 格式化成绩
const formatScore = (score, unit) => {
  if (!score) return '-'
  return `${score}${unit || ''}`
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 获取排名标签类型
const getRankingTagType = (ranking) => {
  const typeMap = {
    1: 'warning',  // 金牌
    2: 'info',     // 银牌
    3: 'success'   // 铜牌
  }
  return typeMap[ranking] || ''
}

// 组件挂载时加载数据
onMounted(() => {
  loadEventOptions()
  loadScoreList()
})
</script>

<style scoped>
.score-query {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 120px);
}

.header-search {
  margin-bottom: 20px;
}

.search-card {
  background-color: #fff;
}

.search-form {
  margin-bottom: 0;
}

.search-form .el-form-item {
  margin-bottom: 0;
}

.table-card {
  background-color: #fff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.score-value {
  font-weight: 600;
  color: #409EFF;
}

.pagination-wrapper {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.score-detail {
  padding: 20px 0;
}

.score-highlight {
  font-size: 18px;
  font-weight: 600;
  color: #409EFF;
}

.detail-remark {
  margin-top: 20px;
}

.detail-remark h4 {
  margin-bottom: 10px;
  color: #303133;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-pagination) {
  justify-content: center;
}
</style>
